var app = getApp();
var clerkModel = require("../../model/clerkModel.js")
var shopModel = require("../../model/shopModel.js")
var util = require("../../utils/util.js")
var times = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: app.data.user,
    dates: [], //日期集合
    records: [], //美容师预约档期记录
    id: 0, //美容师id
    name: "", //美容师名称
    keyword: '', //搜索关键字
    remark:'',
    timeList: [], //时间集合
    dateIndex: 0, //当前选中日期下标
    selectTime: 0, //当前选择的时间
    selectTimeStr: "", //当前选择时间展示字符串
    isShowSelectTime: true, //是否显示时间选择模块
    isShowSelectProject: false, //是否显示项目选择模块

    projectTags: ['全部', '商品', '服务'],
    projectTagIndex: 0,
    goodsList: [], //商品列表
    selectGoodsList: [] //选中商品
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      clerk: app.data.tempClerk
    })
    initTimes();
    this.init();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  init(id) {
    var that = this;
    //获取该店员已预约档期
    util.showLoading("加载中")
    clerkModel.getAppointmentTime(this.data.clerk.uid, res => {
      wx.hideLoading()
      if (res.status == 1) {
        util.failToast(res.msg)
        return;
      }
      that.setData({
        dates: res.data.dates,
        records: res.data.records
      })
      that.updateTimeList(0);
    })
    //加载所有商品
    this.allGoods()
  },
  //提交预约
  bindSubmit() {
    var data = this.data.clerk
    var clerk = {
      uid: data.uid,
      uname: data.uname,
      uimgUrl: data.uimgUrl,
      time: this.data.selectTime,
      remark: this.data.remark,
      projects: this.data.selectGoodsList
    }
    util.showLoading("请稍等..")
    clerkModel.addAppointment(clerk, res => {
      if (res.status == 1) {
        util.failToast(res.msg)
        return;
      }
      wx.hideLoading()
      util.successToast("预约成功")
      setTimeout(()=>{
        wx.redirectTo({
          url: '../user_appointment/user_appointment',
        })
      },1500)
      
    })
  },
  //监听备注输入
  inputRemark(e){
    this.setData({
      remark: e.detail.value
    })
  },
  //=====================时间选择模块=========================
  //更新时间选择标签
  updateTimeList(dateIndex) {
    var records = this.data.records;
    var timeList = [];
    var currentDateTime = this.data.dates[dateIndex].time
    var now = parseInt(new Date().getTime() / 1000); //当前时间戳

    var nowTime = parseInt(now % (24 * 3600)) + 8 * 3600 //现在的时间
    for (var i = 0; i < times.length; i++) {
      var obj = {
        timeStr: times[i].timeStr
      }
      obj.isAppointment = this.getAppointmentState(times[i].time, records, currentDateTime) //是否已预约
      obj.isPast = false; //时间是否已经过了
      if (now > currentDateTime && nowTime > times[i].time) obj.isPast = true
      obj.isSelect = false; //当前是否选中
      var time = this.data.selectTime - currentDateTime
      if (time == times[i].time) {
        obj.isSelect = true;
      }
      timeList.push(obj);
    }
    this.setData({
      timeList: timeList
    })
  },
  //获取档期状态 已预约返回true
  getAppointmentState(time, records, currentDateTime) {
    for (var i = 0; i < records.length; i++) {
      if (time == (records[i].time - currentDateTime)) return true
    }
    return false
  },
  //选择日期
  selectDate(e) {
    var index = e.currentTarget.id
    this.setData({
      dateIndex: index
    })
    this.updateTimeList(index)
  },
  //选择时间
  selectTime(e) {
    var index = e.currentTarget.id
    var today = this.data.dates[this.data.dateIndex]
    var selectTime = times[index].time + today.time
    // var selectTimeStr = today.timeStr + " " + times[index].timeStr
    var selectTimeStr = util.formatTime(selectTime * 1000)
    this.setData({
      selectTime: selectTime,
      selectTimeStr: selectTimeStr
    })
    this.updateTimeList(this.data.dateIndex)
  },
  //显示时间选择窗口
  showSelectTime() {
    this.setData({
      isShowSelectTime: true
    })
  },
  //隐藏时间选择窗口
  hideSelectTime() {
    if (!this.data.selectTime) {
      util.toast('请选择预约时间')
      return;
    }
    this.setData({
      isShowSelectTime: false
    })
  },
  //====================项目选择模块===========================
  //输入框监听
  inputKeyword(e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  //显示项目选择模块
  bindShowProject(e) {
    this.setData({
      isShowSelectProject: !this.data.isShowSelectProject
    })
  },
  //项目选择标签切换
  switchProjectTag(e) {
    var index = e.currentTarget.id
    this.setData({
      projectTagIndex: parseInt(index)
    })
    this.search()
  },
  //加载产品列表
  search() {
    var type = this.data.projectTagIndex
    switch (type) {
      case 0:
        this.allGoods()
        break
      case 1:
        this.getProduct()
        break
      case 2:
        this.getService()
        break
    }
  },
  //获取所有类型产品
  allGoods() {
    var that = this
    util.showLoading("加载中")
    shopModel.allGoods({
      keyword: this.data.keyword
    }, res => {
      wx.hideLoading()
      that.setData({
        goodsList: res.data
      })

      that.updateGoodsState()
    })
  },
  getProduct() {
    var that = this
    util.showLoading("加载中")
    shopModel.getProduct({
      keyword: this.data.keyword
    }, res => {
      wx.hideLoading()
      that.setData({
        goodsList: res.data
      })
      that.updateGoodsState()
    })
  },
  getService() {
    var that = this
    util.showLoading("加载中")
    shopModel.getService({
      keyword: this.data.keyword
    }, res => {
      wx.hideLoading()
      that.setData({
        goodsList: res.data
      })
      that.updateGoodsState()
    })
  },
  //改变商品选中状态
  changeGoodsState(e) {
    var data = e.currentTarget.dataset.data
    var select = e.currentTarget.id
    if (select && select == "true") this.cancleGoods(data)
    else this.selectGoods(data)
  },
  //选中商品
  selectGoods(data) {
    var list = this.data.selectGoodsList
    list.push(data)
    console.log(list)
    this.setData({
      selectGoodsList: list
    })
    this.updateGoodsState()
  },
  //取消选中
  cancleGoods(data) {
    var list = this.data.selectGoodsList
    var position = getPosition(list, data)
    if (position != -1) list.splice(position, 1)
    this.setData({
      selectGoodsList: list
    })
    this.updateGoodsState()
  },
  //更新商品列表选择状态
  updateGoodsState() {
    var selectGoodsList = this.data.selectGoodsList
    var goodsList = this.data.goodsList
    for (var i = 0; i < goodsList.length; i++) {
      var obj = goodsList[i]
      obj.select = getPosition(selectGoodsList, obj) == -1 ? false : true
    }
    this.setData({
      goodsList: goodsList
    })
  }

})

var startTimeStr = "08:00"
var endTimeStr = "21:30"
//初始化时间标签,08:00~21:30
function initTimes() {
  var startTime = str2Time(startTimeStr);
  var endTime = str2Time(endTimeStr);
  var len = (endTime - startTime) / (30 * 60)
  for (var i = 0; i <= len; i++) {
    var time = startTime + i * 30 * 60
    var timeStr = time2Str(time)
    times[i] = {
      time: time,
      timeStr: timeStr
    }
  }
}

function str2Time(str) {
  var arr = str.split(":")
  return parseInt(arr[0]) * 3600 + parseInt(arr[1]) * 60
}

function time2Str(time) {
  var h = parseInt(time / 3600);
  var m = parseInt(time % 3600 / 60);
  return [h, m].map(util.formatNumber).join(":");
}

//获取商品在数组位置
function getPosition(arr, obj) {
  for (var i = 0; i < arr.length; i++) {
    var node = arr[i]
    if (node.id == obj.id && node.type == obj.type) {
      return i
    }
  }
  return -1
}